package com.heima.tlias.interceptor;

import cn.hutool.core.util.StrUtil;
import com.heima.tlias.utils.JwtUtil;
import com.heima.tlias.utils.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 登录校验
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String threadName = Thread.currentThread().getName();
        log.info("LoginInterceptor 当前线程名称:{}", threadName);

        //1. 获取请求中的token
        String token = request.getHeader("token");
        //2. 判断token令牌是否存在
        if (StrUtil.isEmpty(token)) {
            //2.1 不存在 校验失败 返回 401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //2.2 存在 校验token
        Map<String, Object> claims = JwtUtil.parseJwt(token);
        //3. 解析token , 获取解析结果
        if (claims == null) {
            //3.1 解析失败 校验失败返回401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //保存数据到当前线程
        int userId = Integer.parseInt(claims.get("id").toString());
        UserThreadLocalUtil.set(userId);

        //3.2 解析成功 , 校验通过, 直接放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理线程中的数据防止内存泄漏
        UserThreadLocalUtil.remove();
    }
}
